package com.qingcheng.timer;

import com.qingcheng.dao.SeckillGoodsMapper;
import com.qingcheng.pojo.seckill.SeckillGood;
import com.qingcheng.utils.CacheKey;
import com.qingcheng.utils.DateUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * Created by yuanxin
 * Date:2019/7/20
 * Time:19:08
 */
@Component
public class SeckillGoodsTask {
    @Autowired
    private SeckillGoodsMapper seckillGoodsMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 定时任务方法---加载秒杀商品进缓存
     * 0/30 * * * * ?:从每分钟的第0秒开始执行，每过30秒执行一次
     */
    @Scheduled(cron = "0/30 * * * * ?")
    public void loadGoodsPushRedis() {
        List<Date> dateMenus = DateUtil.getDateMenus();
        for (Date startTime : dateMenus) {
            String extName = DateUtil.date2Str(startTime);
            String key = "SeckillGoods_" + extName;
            Example example = new Example(SeckillGood.class);
            Example.Criteria criteria = example.createCriteria();
            criteria.andEqualTo("status", "1");
            criteria.andGreaterThan("stockCount", 0);
            criteria.andGreaterThanOrEqualTo("startTime",startTime);
            criteria.andLessThanOrEqualTo("endTime", DateUtil.addDateHour(startTime,2));
            Set keys = redisTemplate.boundHashOps(key).keys();
            if (keys != null && keys.size() > 0) {
                criteria.andNotIn("id",keys);
            }

            List<SeckillGood> seckillGoods = seckillGoodsMapper.selectByExample(example);
            for (SeckillGood seckillGood : seckillGoods) {
                redisTemplate.boundHashOps(key).put(seckillGood.getId(),seckillGood);
                Long[] ids = pushIds(seckillGood.getStockCount(), seckillGood.getId());
                redisTemplate.boundListOps(CacheKey.SECKILLGOODSCOUNTLIST_.toString()+seckillGood.getId()).leftPushAll(ids);

                //解决数据不精准
                redisTemplate.boundHashOps(CacheKey.SECKILLGOODSCOUNT).increment(seckillGood.getId(),seckillGood.getStockCount());
            }
        }
    }

    /**
     * 将商品ID存入到数组中
     * @param len
     * @param id
     * @return
     */
    public Long[] pushIds(int len,Long id){
        Long[] ids = new Long[len];
        for (int i = 0; i < ids.length; i++) {
            ids[i]=id;
        }
        return ids;
    }
}
